import { debounceTime } from 'rxjs/operators'
import {
  Component,
  OnInit,
  ViewChild,
  AfterViewInit,
  OnDestroy,
} from '@angular/core'
import { ResourceVisualizaitonService } from 'src/app/service/resource-visualization.service'
import { Subscription, Subject } from 'rxjs'
import { KspMapService } from 'src/app/base/map/kspmap.service'
import { SearchTypeSetting } from './seach-panel/search-panel.model'
import { MapLabelEditor } from './resource-visualization.model'
import { HttpsApiService } from '../../httpApi/http-api.service'
import { UtilService } from '../../base/util/utilService'
import { AuthService } from '../../auth/auth.service'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import { MapUtils } from '../../@map/map-utils'
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router'
import * as ol from 'openlayers'
import * as $ from 'jquery'
import { Kspmap } from '../../base/map/model/map-lib/map/Kspmap'
import { IncidentService } from '../../service/incident.service'
import { GIS_OVERVIEW_WMS_URL } from 'src/app/config/project.config'
import {
  KspFeatureTypeConfig,
  KspFeature,
} from '../../base/map/model/feature.model'
import { FeaturesSelectorComponent } from '../../components/features-selector/features-selector.component'
import { SearchPanelService } from './seach-panel/search-panel.service'
import { GIS_HOME_PATH } from 'src/app/config/routes.config'
import { TOPIC_HOME_PATH } from '../../config/routes.config'
import { MenuSelectServices } from '../../service/menu-select.service'
import { LayerConstant } from 'src/app/base/map/model/map-lib/map/layer/LayerConstant'
import { environment } from 'src/environments/environment'
import { MapUtilsModel } from 'src/app/@map/model/mapUtils.model'
import { RangerEditorModel } from 'src/app/@map/panel-model/ranger.model'
import { GisPropagateComponent } from '../../components/all-popups/gis-propagate/gis-propagate.component'

@Component({
  selector: '',
  templateUrl: './resource-visualization.component.html',
  styleUrls: ['./resource-visualization.component.scss'],
})
export class ResourceVisualizationComponent
  implements OnInit, AfterViewInit, OnDestroy
{
  isVisible
  nzFooter = null
  dataList
  rooterChange: Subscription
  @ViewChild('featureSelector', null)
  featureSelector: FeaturesSelectorComponent
  featureSelectorOverlayer = new ol.Overlay({
    stopEvent: true,
    // autoPan: true,
    offset: [0, -20],
  })
  labelType = 'KSP_FST_LABEL'
  showRegionSearchBtn = false
  subscription: Subscription
  rollSearchBox = false
  labelEditElement: HTMLElement
  labelEditOverlayId = 'label-edit'
  labelIconIdCount = 0
  labelIconIds = []
  labelIconType = 1

  currentLabelFeature: any
  kspMap
  hideListBtnStatus = false
  operation = 'SearchList'
  labelIconSize: [32, 32]
  mapUtils = new MapUtils(this.kspMapService)
  timer = null
  // 行政区划 wfs服务
  GdTile
  geojsonLayer = null
  wmsview
  map: Kspmap
  wmsparams
  wmsLayer: ol.layer.Vector
  pointTitleLayer: ol.layer.Vector
  tool_bar_org
  // 当前显示的feature  和等级
  wfsFeature = {
    feature: null,
    cql: '',
    zoom: 0,
    rpno: '', // 父级no
  }
  userWfsOrg = ''
  userOrgName = ''
  userWfszoom = 0
  userWfsExtent: any
  // 缓存的feature
  wfsFeatures = {
    zooms: [], // 对应的子zoom
    features: {}, // 对应的子feature
    cql_feature: {}, // 对应的当前feature
  }
  globalcount = 0
  viewExtentCount = 0
  // 行政区  全局选中变量
  globalAdministrative: {
    zoom: 0
    administrative: {}
  }
  //  记录的点击和划入方法(要删除的)
  singleclick
  pointermove
  resoluption
  gisHomePath: string = GIS_HOME_PATH
  firstInitHomePage: boolean = true
  toolboolean = true
  toolAfter = false
  resolutionSubject = new Subject()
  resolutionObservable = this.resolutionSubject.asObservable().pipe(debounceTime(500))
  // 行政区划 wfs服务
  resolutiontSubscription: Subscription
  homeInitSubjectSubscription: Subscription
  orgTreefarmSubscription: Subscription
  searchPanelServiceSubscription: Subscription
  IncidentServiceSubscription: Subscription
  spotSubscription: Subscription
  organnoSpotSubscription: Subscription
  wmsExtentParams: {
    service: string
    version: string
    request: string
    typeNames: string
    srsname: string
    outputFormat: string
    cql_filter: string
  }
  sumOrganName: any
  setViewInterval: NodeJS.Timer
  baseMapLayerChangedSubscription: Subscription
  isShowGdTile = true
  /**
   * @description 首页省属林场是否显示
   */
  isorgTreefarm = true
  /**
   * @description 图斑是否显示
   */
  spotBoolean = true
  trackLegend = false
  trackType = 'track'
  overMap = environment.overMap
  view = new ol.View({
    center: ol.proj.fromLonLat([5.8713, 45.6452]),
    zoom: 19,
  })
  geolocation = new ol.Geolocation({
    projection: this.view.getProjection(),
    trackingOptions: {
      maximumAge: 10000,
      enableHighAccuracy: true,
      timeout: 600000,
    },
  })
  PersonalModel = new RangerEditorModel()
  layerConfig = {
    id: 'personal_point',
    name: '个人坐标点矢量图标',
  }
  points = []
  pointe = []
  timers = null
  model
  olMap: ol.Map

  masklayer //遮照图层
  initfeatureGeometry //初始化的蒙版数据
  userworkinfo //初始化机构
  isprotection=false //是否显示保护资源模块
  protectionid=null //是否显示保护区图层
  innerLayer
  outerLayer
  constructor(
    private resourceVisualService: ResourceVisualizaitonService,
    private kspMapService: KspMapService,
    private https: HttpsApiService,
    private utils: UtilService,
    private router: Router,
    private message: NzMessageService,
    private rvService: ResourceVisualizaitonService,
    private route: ActivatedRoute,
    private authService: AuthService,
    private IncidentService: IncidentService,
    public searchPanelService: SearchPanelService,
    private menuService: MenuSelectServices,
    private modalService: NzModalService
  ) {
    if (!environment.official) {
      this.baseMapLayerChangedSubscription =
        this.kspMapService.$baseMapLayerChanged.subscribe((layerConfig) => {
          this.isShowGdTile = layerConfig['type'] === LayerConstant.TIANDITU_RS
          this.setLayerConfigVisiblity()
        })
    }
    // 关闭省属林场显示
    this.orgTreefarmSubscription =
      this.resourceVisualService.$treefarmObservable.subscribe((data) => {
        this.treeFarmisShow(data)
      })

    this.homeInitSubjectSubscription =
      this.resourceVisualService.$homeInitSubjectObservable.subscribe(
        (data) => {
          this.IncidentService.nextPanelCLick('all-detail')
          this.IncidentService.nextPanelCLick('Pop-ups')
          this.IncidentService.nextPanelCLick('task-detail')
          this.showIndexHome()
        }
      )
    if (this.router.url !== this.gisHomePath) {
      this.firstInitHomePage = false
    }
    this.rooterChange = this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        if (event.url === this.gisHomePath || event.url === TOPIC_HOME_PATH) {
          this.toolboolean = true
        } else {
          this.searchAvailable = true
          this.toolboolean = false
          this.isprotection=false
          this.protectionid=null
        }
      }
    })
    this.searchPanelServiceSubscription =
      this.searchPanelService.$subjectMapClickObservable.subscribe((data) => {
        console.log(data)
        if (data != undefined) {
          this.PseudongAfterViewInit(data)
        }
      })
    this.IncidentServiceSubscription =
      this.IncidentService.$AlertClickObservable.subscribe((data) => {
        if (data === 'Pop-ups') {
          this.rvService.removeAllModal()
          this.isprotection=false
          this.protectionid=null
        }
      })

    this.spotSubscription =
      this.resourceVisualService.$spotObservable.subscribe((ldata: any) => {
        if (ldata.type === 'spot') {
          this.spotBoolean = !ldata.isshow
        } else if ('track') {
          this.trackLegend = ldata.isshow
          this.trackType = ldata.trackType
        }
      })
    this.organnoSpotSubscription =
      this.resourceVisualService.$spotorgObserbable.subscribe((data: any) => {
        if (data.spotorg) {
          this.wmsparams.cql_filter = 'rpno=' + data.no
          this.wmsExtentParams.cql_filter = 'rno=' + data.no
          // this.wfsFeature.feature = feature
          // this.wfsFeatures.cql_feature[this.wmsparams.cql_filter] = feature
          this.wfsFeature.rpno = 'rpno=' + data.rpno

          this.selectcache(true)
        }
      })

      this.IncidentServiceSubscription = this.IncidentService.$AlertClickObservable.subscribe(
        (data) => {
          if (data ==='hide-protection') {
            this.isprotection=false
            this.protectionid=null
          }
        }
      )

  }

  /**
   * @description 首页图层 是否显示省属林场
   * @param {*} boolean false:显示 / true :不显示
   */
  treeFarmisShow(boolean) {
    this.isorgTreefarm = boolean
    this.pointTitleLayer.getSource().refresh()
    this.wmsLayer.getSource().refresh()
  }
  showPosition = (position) => {
    let lat = position.coords.latitude
    let lng = position.coords.longitude
    let wkt = 'SRID=4326;POINT(' + lng + ' ' + lat + ')'
    console.log('成功', position, wkt)
    this.mapUtils.removeVectorLayer('personal_point')
    this.points = []
    this.pointe = []
    console.log(KspFeatureTypeConfig.hotspot, KspFeatureTypeConfig.personal)
    console.log(KspFeatureTypeConfig.personal.type)
    const point = new KspFeature({
      id: this.authService.getAccountInfo().employeeId,
      type: KspFeatureTypeConfig.personal.type,
      geometry: {
        type: 'point',
        points: MapUtilsModel.getWkt([wkt]),
      },
      title: '个人位置',
      hoverText: '个人位置',
    })
    this.points.push(point)
    this.pointe.push(MapUtilsModel.getWkts([wkt])[0])
    this.mapInit()
  }
  // 错误与拒绝处理
  showError = (error) => {
    clearInterval(this.timers)
    switch (error.code) {
      case error.PERMISSION_DENIED:
        this.message.error('获取失败，您拒绝了获取地理位置的请求！')
        break
      case error.POSITION_UNAVAILABLE:
        this.message.error('获取失败，您的位置信息不可用！')
        break
      case error.TIMEOUT:
        this.message.error('获取失败，请求地理位置超时！')
        break
      case error.UNKNOWN_ERROR:
        this.message.error('获取失败，发生未知错误！')
        break
    }
  }
  ngOnInit() {
    let UA = navigator.userAgent
    if (/android|adr/gi.test(UA)) {
      this.model = 'isAndroid'
    } else if (/iphone|ipod|ipad/gi.test(UA) && this.model !== 'isAndroid') {
      this.model = 'isIos'
    } else {
      this.model = 'windows'
      // this.model = 'isAndroid'
    }
    console.log(UA, this.model)
    if (navigator.geolocation && this.model !== 'windows') {
      console.log('浏览器支持!')
      console.log(navigator.geolocation)
      window.navigator.geolocation.getCurrentPosition(
        this.showPosition,
        this.showError
      )
      this.timers = setInterval(() => {
        window.navigator.geolocation.getCurrentPosition(
          this.showPosition,
          this.showError
        )
      }, 30000)
    } else {
      console.log('浏览器不支持!')
    }
  }
  mapInit() {
    this.mapUtils.removeVectorLayer(this.layerConfig.id)
    this.PersonalModel.pointsCreateVectorLayer(
      this.points,
      this.mapUtils,
      this.layerConfig
    )
  }
  ngAfterViewInit() {
    this.kspMap = this.kspMapService.getKspmap()
    this.kspMap.addMapEvent('singleclick', this.mapClick)
    this.map = this.kspMapService.getKspmap()
    this.olMap = this.map.mainMap
    this.addGdTile()
    this.addRegionLineLayer()
    // 行政区划
    this.initparams()
    this.initExtentparams()
    this.pointermove = this.map.mainMap.on('pointermove', this.mapPointermove)

   this.userworkinfo = ''
    const _user = this.utils.getSessionStorage('ksp_t')
    console.log('_user=======', _user)
    if (_user) {
      if (_user['department'] !== 0) {
        this.userworkinfo = _user['organPNo']
      } else {
        this.userworkinfo = _user['organNo'] || '44'
      }
      console.log(_user)
      this.userOrgName = _user['organName']
    } else {
      this.userworkinfo = '44'
    }
    this.wmsparams.cql_filter = 'rpno=' + this.userworkinfo
    this.wmsExtentParams.cql_filter = 'rno=' + this.userworkinfo
    this.userWfsOrg = 'rpno=' + this.userworkinfo
    
    this.wmsHoverLayer()
    this.selectcache()
  
    this.kspMap.bindChangeResolutionEvent((evt) => {
      this.onResolutionChanged(evt)
    })
    if (this.firstInitHomePage) {
      setTimeout(() => {
        this.searchAvailable = false
      }, 200)
    }
    this.featureSelectorOverlayer.setElement(
      this.featureSelector.getNativeElement()
    )
    this.kspMap.mainMap.addOverlay(this.featureSelectorOverlayer)
    this.resolutiontSubscription = this.resolutionObservable.subscribe(
      (data) => {
        this.moveed(data)
      }
    )


  
  }




  moveed = (e) => {
    console.warn('moveed')
    this.geojsonLayer.getSource().clear()
    this.setLayerConfigVisiblity()
    let zoom = this.kspMap.mainMap.getView().getZoom()
    // return
    console.log(
      '地图当前resolution' + this.kspMap.mainMap.getView().getResolution()
    )
    console.log('地图当前zoom' + this.kspMap.mainMap.getView().getZoom())
    zoom = Math.floor(zoom)
    if (Number.isInteger(zoom)) {
      if (
        this.wfsFeature.zoom !== zoom &&
        // this.wfsFeature.zoom + 1 >= zoom &&
        this.wfsFeature.zoom + 1 !== zoom &&
        this.wmsparams.cql_filter !== this.userWfsOrg
      ) {
        if (this.userWfszoom + 1 >= zoom) {
          this.wmsparams.cql_filter = this.userWfsOrg
          this.selectcache()
          // 显示行政区冒泡
          this.resolveAdministrative(this.userWfsOrg, this.userOrgName)
        } else {
          // this.geojsonLayer.getSource().clear()
          // this.wmsLayer.getSource().clear()
          this.wfsBackShow(zoom)
          // // 删除行政区冒泡
          // this.resolveAdministrative(null, null)
        }
      } else {
        if (
          this.wmsparams.cql_filter === this.userWfsOrg &&
          this.userWfszoom + 2 <= zoom
        ) {
          this.geojsonLayer.getSource().clear()
          this.wmsLayer.getSource().clear()
          // 删除行政区冒泡
          this.resolveAdministrative(null, null)
        } else if (
          this.wmsparams.cql_filter === this.userWfsOrg &&
          this.userWfszoom - 2 <= zoom
        ) {
          this.wmsparams.cql_filter = this.userWfsOrg

          this.selectcache()
          // 显示行政区冒泡
          this.resolveAdministrative(this.userWfsOrg, this.userOrgName)
        } else {
          this.wfsBackShow(zoom)
        }
      }

      // end 行政区
      // }, 1000)
    }
    if(zoom <= 8){
        this.masklayer.setVisible(false)
        this.innerLayer.setVisible(false)
        this.outerLayer.setVisible(false)
    }else{
      this.masklayer.setVisible(true)
      this.innerLayer.setVisible(true)
      this.outerLayer.setVisible(true)
    }
  }

  mapPointermove = (event) => {
    this.resourceVisualService.nextaddHoverSubject(null)
    // 行政区hover
    this.geojsonLayer.getSource().clear()
    if (event['dragging']) {
      return
    }
    let feature = this.map.mainMap.forEachFeatureAtPixel(
      event['pixel'],
      (feature) => {
        return feature
      }
    )
    let featureBoolean = false
    if (this.wfsFeatures.features[this.wmsparams.cql_filter]) {
      featureBoolean = this.wfsFeatures.features[
        this.wmsparams.cql_filter
      ].some((e) => e === feature)
    }

    if (featureBoolean) {
      this.geojsonLayer.getSource().addFeature(feature)
      this.resourceVisualService.nextaddHoverSubject(feature)
    }
  }

  PseudongAfterViewInit(data) {
    this.PseudomapClick(data)
    // this.kspMap = this.kspMapService.getKspmap()
    // this.kspMap.addMapEvent('singleclick', this.PseudomapClick(data))
    // this.kspMap.addMapEvent('pointerdrag', this.mapPointerDrag)
  }
  PseudomapClick(e) {
    console.log(e)
    var coordinate = e['position']
    if (e['dataList'] != undefined) {
      this.featureSelector.setDataLists(e['dataList'], 'type')
    } else {
      if (e['data']['data']['type'] === 'realtimeSeekhelp') {
        this.featureSelector.setDataList(
          e['data']['data']['id'],
          'panel_ranger_point_type'
        )
      } else if (e['data']['data']['type'] === 'panel_ranger_point_type') {
        this.featureSelector.setDataList(
          e['data']['rangerId'],
          'panel_ranger_point_type'
        )
      } else if (e['data']['data']['type'] === 'police') {
        this.featureSelector.setDataList(
          e['data']['id'],
          'police'
        )
      } else if (e['data']['data']['type'] === 'patrolapp') {
        this.featureSelector.setDataList(e['data']['id'], 'patrolapp')
      } else if (e['data']['data']['type'] === 'insect') {
        this.featureSelector.setDataList(e['data']['id'], 'insect')
      } else if (e['data']['data']['type'] === 'trap') {
        this.featureSelector.setDataList(e['data']['id'], 'trap')
      } else if (e['data']['data']['type'] === 'meteorolog') {
        this.featureSelector.setDataList(e['data']['id'], 'meteorolog')
      } else if (e['data']['data']['type'] === 'incident') {
        this.featureSelector.setDataList(e['data']['id'], 'incident')
      } else if (e['data']['data']['type'] === 'hotspot') {
        this.featureSelector.setDataList(e['data']['id'], 'hotspot')
      } else if (e['data']['data']['type'] === 'sensing-polygon') {
        this.featureSelector.setDataList(e['data']['id'], 'sensing-polygon')
      } else if (e['data']['data']['type'] === 'video') {
        this.featureSelector.setDataList(e['data']['id'], 'video')
      } else if (e['data']['data']['type'] === 'mission') {
        // this.queryPropagate(e['data']['id'])
        const modal = this.modalService.create({
          nzClosable: false,
          nzContent: GisPropagateComponent,
          nzWidth: 520,
          nzFooter: null,
          nzMask: true,
          nzMaskClosable: false,
          nzBodyStyle: {
            padding: 0,
            height: '100%',
            overflow: 'hidden',
          },
          nzStyle: {
            padding: '0',
          },
          nzComponentParams: {
            id: e['data']['id'],
          },
        })
        modal.afterClose.subscribe((data) => {})
        return
        // this.featureSelector.setDataList(e['data']['id'], 'mission')
      } else if (e['data']['data']['type'] === 'harmful') {
        this.featureSelector.setDataList(e['data']['id'], 'harmful')
      } else if (e['data']['data']['type'] === 'primaryClass') {
        this.featureSelector.setDataList(e['data']['id'], 'primaryClass')
      } else if (e['data']['data']['type'] === 'protection') {
        this.isprotection=true
        this.protectionid=e['data']['id']
        this.featureSelector.setDataList(e['data']['id'], 'protection')
      } else if (e['data']['data']['type'] === 'thematic') {
        this.featureSelector.setDataList(e['data']['id'], 'thematic')
      } else if (e['data']['data']['type'] === 'position') {
        this.featureSelector.setDataList(e['data']['id'], 'position')
      } else if (e['data']['data']['type'] === 'uav') {
        this.featureSelector.setDataList(e['data']['id'], 'uav')
      } else if (
        e['data']['data']['type'] === KspFeatureTypeConfig.topic.type
      ) {
        this.featureSelector.setDataList(
          e['data']['id'],
          KspFeatureTypeConfig.topic.type
        )
      }else if (e['data']['data']['type'] === 'customImport') {
        e['data']['data']['teid']=e['data']['data']['data'].id
        this.featureSelector.setData(e['data']['data']['data'], 'customImport')
      } else {
        this.featureSelector.setDataList(0, 'null')
      }
    }

    this.featureSelectorOverlayer.setElement(
      this.featureSelector.getNativeElement()
    )
    this.featureSelectorOverlayer.setPosition(coordinate)
    console.log(coordinate)
    this.kspMap.mainMap.addOverlay(this.featureSelectorOverlayer)
    this.kspMap.setMapCenter(coordinate)

    return
  }
  // 地图点击监听函数
  mapClick = (event) => {
    this.geojsonLayer.getSource().clear()
    const e = event
    console.log(e)
    var coordinate = e['position']
    let labelClick = false
    if (
      event.feature &&
      event.feature!.getProperties() &&
      event.feature!.getProperties().data.data.type ===
        KspFeatureTypeConfig.videoSum.type
    ) {
      // const levelid = event.feature.getProperties().data.data.levelid
      // const sumCoordinate = event.feature.getProperties().data.data.coordinate
      // if (levelid && levelid === 4) {
      //   this.kspMap.setMapCenterAndZoom(sumCoordinate, 13)
      //   return
      // }

      console.warn(event.feature)

      this.sumOrganName = event.feature!.getProperties().data.data.sumOrganName
      let sumOrganno = event.feature!.getProperties().data.data.sumOrganno

      this.wfsFeatures.features[this.wmsparams.cql_filter].forEach(
        (f: ol.Feature) => {
          if (f!.getProperties().rno === sumOrganno) {
            this.wfsFeature.feature = f
            this.wfsFeatures.cql_feature['rpno=' + sumOrganno] = f
            return
          }
        }
      )
      this.wmsparams.cql_filter = 'rpno=' + sumOrganno
      this.wmsExtentParams.cql_filter = 'rno=' + sumOrganno

      this.selectcache()
      return
    }
    if (e['dataList'] != undefined) {
      this.featureSelector.setDataLists(e['dataList'], 'type')
      this.featureSelectorOverlayer.setElement(
        this.featureSelector.getNativeElement()
      )
      this.featureSelectorOverlayer.setPosition(coordinate)
      this.kspMap.setMapCenter(coordinate)
    } else if (e['data']) {
      if (e['data']['data']['type'] === 'realtimeSeekhelp') {
        this.featureSelector.setDataList(
          e['data']['data']['id'],
          'panel_ranger_point_type'
        )
      } else if (e['data']['data']['type'] === 'panel_ranger_point_type') {
        this.featureSelector.setDataList(
          e['data']['id'],
          'panel_ranger_point_type'
        )
      } else if (e['data']['data']['type'] === 'police') {
        this.featureSelector.setDataList(
          e['data']['id'],
          'police'
        )
      } else if (e['data']['data']['type'] === 'patrolapp') {
        this.featureSelector.setDataList(e['data']['id'], 'patrolapp')
      } else if (e['data']['data']['type'] === 'insect') {
        this.featureSelector.setDataList(e['data']['id'], 'insect')
      } else if (e['data']['data']['type'] === 'trap') {
        this.featureSelector.setDataList(e['data']['id'], 'trap')
      } else if (e['data']['data']['type'] === 'meteorolog') {
        this.featureSelector.setDataList(e['data']['id'], 'meteorolog')
      } else if (e['data']['data']['type'] === 'incident') {
        this.featureSelector.setDataList(e['data']['id'], 'incident')
      } else if (e['data']['data']['type'] === 'hotspot') {
        this.featureSelector.setDataList(e['data']['id'], 'hotspot')
      } else if (e['data']['data']['type'] === 'seedling') {
        this.featureSelector.setDataList(e['data']['id'], 'seedling')
      } else if (e['data']['data']['type'] === 'sensing-polygon') {
        this.featureSelector.setDataList(e['data']['id'], 'sensing-polygon')
      } else if (e['data']['data']['type'] === 'video') {
        this.featureSelector.setDataList(e['data']['id'], 'video')
      } else if (e['data']['data']['type'] === 'primaryClass') {
        this.featureSelector.setDataList(e['data']['id'], 'primaryClass')
      } else if (e['data']['data']['type'] === 'protection') {
        this.isprotection=true
        this.protectionid=e['data']['id']
        this.featureSelector.setDataList(e['data']['id'], 'protection')
      } else if (e['data']['data']['type'] === 'thematic') {
        this.featureSelector.setDataList(e['data']['data']['id'], 'thematic')
      } else if (e['data']['data']['type'] === 'mission') {
        const modal = this.modalService.create({
          nzClosable: false,
          nzContent: GisPropagateComponent,
          nzWidth: 520,
          nzFooter: null,
          nzMask: true,
          nzMaskClosable: false,
          nzBodyStyle: {
            padding: 0,
            height: '100%',
            overflow: 'hidden',
          },
          nzStyle: {
            padding: '0',
          },
          nzComponentParams: {
            id: e['data']['id'],
          },
        })
        modal.afterClose.subscribe((data) => {})
        // this.queryPropagate(e['data']['id'])
        return
        // this.featureSelector.setDataList(e['data']['data']['id'], 'mission')
      } else if (e['data']['data']['type'] === 'harmful') {
        this.searchPanelService.position = e['position']
        this.featureSelector.setDataList(e['data']['data']['id'], 'harmful')
      } else if (e['data']['data']['type'] === 'position') {
        this.featureSelector.setDataList(e['data']['data']['id'], 'position')
      } else if (e['data']['data']['type'] === 'uav') {
        this.featureSelector.setDataList(e['data']['data']['id'], 'uav')
      } else if (e['data']['data']['type'] === 'uav-patrol') {
        this.featureSelector.setData(e['data']['data'], 'uav-patrol')
      } else if (e['data']['data']['type'] === 'panel_search-label') {
        this.resourceVisualService.nextlabelClickEvent(e)
        labelClick = true
      } else if (
        e['data']['data']['type'] === KspFeatureTypeConfig.topic.type
      ) {
        this.featureSelector.setDataList(
          e['data']['data']['id'],
          KspFeatureTypeConfig.topic.type
        )
      } else {
        // this.featureSelector.setDataList(0, 'null')
        return
      }
      if (!labelClick) {
        this.featureSelectorOverlayer.setElement(
          this.featureSelector.getNativeElement()
        )
        this.featureSelectorOverlayer.setPosition(coordinate)
        this.kspMap.setMapCenter(coordinate)
      } else {
      }
      // this.kspMap.setMapCenterAndZoom(coordinate, 15)
    }

    let feature = event['regionFeature']
    if (!feature) {
      return
    }
    let featureBoolean = this.wfsFeatures.features[
      this.wmsparams.cql_filter
    ].some((e) => e === feature)
    // if (
    //   feature &&
    //   feature.getProperties() &&
    //   feature.getProperties().levelid === 4
    // ) {
    //   // 镇级地图  没有操作
    //   return
    // }
    if (featureBoolean) {
      this.wmsparams.cql_filter = 'rpno=' + feature!.getProperties().rno
      this.wmsExtentParams.cql_filter = 'rno=' + feature!.getProperties().rno
      this.wfsFeature.feature = feature
      this.wfsFeatures.cql_feature[this.wmsparams.cql_filter] = feature
      this.wfsFeature.rpno = 'rpno=' + feature!.getProperties().rpno

      this.selectcache()
    }
  }
  /**
   * @description 查询wfs缓存
   * @param {*} [stopExtent] 图斑联动返回上一级  居中
   */
  selectcache(stopExtent?) {
    let boolean = true
    for (let o in this.wfsFeatures.features) {
      console.log(this.wfsFeatures.features)
      if (this.wmsparams.cql_filter === o) {
        boolean = false
        this.geojsonLayer.getSource().clear()
        this.wmsLayer.getSource().clear()
        this.wmsLayer.getSource().addFeatures(this.wfsFeatures.features[o])
        // 
        // 充缓存里面 获取当前等级
        let extent = null
        this.wfsFeatures.zooms.some((z) => {
          if (z.cql === this.wmsparams.cql_filter) {
            this.wfsFeature.zoom = z.zoom
            extent = z.extent
            return true
          }
        })
        if (this.userWfsOrg !== this.wmsparams.cql_filter || stopExtent) {
          this.map.mainMap.getView().fit(extent, {
            size: this.map.mainMap.getSize(),
            padding: [0, 0, 0, 0],
            duration: 1000,
          }) //居中到geometry视野中
        }
        // return
      }
    }
    // 没有缓存  调用搜索方法
    if (boolean) {
      this.addAdministrativeLayer()
    } else {
      this.setAdministrative()
    }
  }

  /**
   * @description wfs后退显示行政区划
   */
  wfsBackShow(zoom) {
    if (this.wfsFeature.rpno === this.userWfsOrg) {
      return
    }
    let backisShow = true
    // 自己回退显示
    if (zoom >= this.wfsFeature.zoom && zoom - 1 <= this.wfsFeature.zoom) {
      this.wmsLayer.getSource().clear()
      this.wmsLayer
        .getSource()
        .addFeatures(this.wfsFeatures.features[this.wfsFeature.cql])
      // 有缓存
      this.wmsparams.cql_filter = this.wfsFeature.cql

      this.setAdministrative()
      backisShow = false
    }
    // 自己回退没有  调用监测  父级回退显示
    if (backisShow) {
      this.wfsFeatures.zooms.forEach((z) => {
        if (z.cql === this.wfsFeature.rpno) {
          this.recursiveAdministrative(
            zoom,
            this.wfsFeature.cql,
            this.wfsFeature.rpno,
            this.wfsFeature.zoom,
            z.zoom
          )
          return
        }
      })
      // for (let z of this.wfsFeatures.zooms) {
      //   if (z.cql === this.wfsFeature.rpno) {
      //     let zoomdiffer = this.wfsFeature.zoom - z.zoom
      //     if (zoom + 1 >= z.zoom && zoom - zoomdiffer <= z.zoom) {
      //       this.wmsLayer
      //         .getSource()
      //         .addFeatures(this.wfsFeatures.features[this.wfsFeature.rpno])
      //       // 有缓存
      //       this.wmsparams.cql_filter = this.wfsFeature.rpno
      //       this.wfsFeature.zoom = z.zoom

      //       this.setAdministrative()
      //     }
      //     return
      //   }
      // }
    }
  }
  /**
   * @description
   * @param {*} zoom 当前zoom
   * @param {*} _cql 当前显示的 行政区
   * @param {*} father_cql 当前显示父的 行政区
   * @param {*} _cql_zoom 当前显示的 zoom
   * @param {*} father_cql_zoom 当前显示父的 zoom
   */
  recursiveAdministrative(zoom, _cql, father_cql, _cql_zoom, father_cql_zoom) {
    let zoomdiffer = _cql_zoom - father_cql_zoom
    if (zoom + 1 >= father_cql_zoom && zoom - zoomdiffer <= father_cql_zoom) {
      this.wmsLayer.getSource().clear()
      this.wmsLayer
        .getSource()
        .addFeatures(this.wfsFeatures.features[father_cql])
      // 有缓存
      this.wmsparams.cql_filter = father_cql
      this.wfsFeature.zoom = father_cql_zoom
      if (this.wfsFeatures!.cql_feature![father_cql]) {
        this.wfsFeature.rpno =
          'rpno=' +
            this.wfsFeatures!.cql_feature![father_cql]!.getProperties().rpno ||
          null
      }

      this.setAdministrative()
    } else {
      let cql = ''
      if (this.wfsFeatures!.cql_feature[father_cql]) {
        cql =
          'rpno=' +
            this.wfsFeatures!.cql_feature![father_cql]!.getProperties().rpno ||
          null
      }

      if (!cql || cql === this.userWfsOrg || father_cql === this.userWfsOrg)
        return
      this.wfsFeatures.zooms.forEach((z) => {
        if (z.cql === cql) {
          this.recursiveAdministrative(
            zoom,
            father_cql,
            cql,
            father_cql_zoom,
            z.zoom
          )
          return
        }
      })
    }
  }
  /**
   * @description 解析行政区 传值
   * @param {*} org 最大行政区编号
   * @param {*} name 最大行政区名称
   */
  resolveAdministrative(org, name) {
    let cql_filter = 'rpno='
    let featuresExtent = null
    if (org) {
      featuresExtent = []
      let features = this!.wfsFeatures!.features[org]

      // console.log(features)
      features.some((f) => {
        let levelid = f!.getProperties().levelid

        if (levelid > 4) {
          return true
        }
        featuresExtent.push({
          org: f!.getProperties().rno,
          levelid,
          coordinate: ol.extent.getCenter(f.getGeometry().getExtent()),
        })
      })

      org = this.wmsparams.cql_filter.substr(
        cql_filter.length,
        this.wmsparams.cql_filter.length
      )

        console.log(featuresExtent)

      this.onOrganChanged(org, featuresExtent, name)
    } else {
      this.onOrganChanged(org, null, name)
    }
  }
  /**
   * @description 设置行政区
   */
  setAdministrative() {
    let cql_filter = 'rpno='
    let org = null
    let rname = null
    let featuresExtent = []

    if (this.wfsFeature.cql !== this.wmsparams.cql_filter) {
      org = this.wmsparams.cql_filter.substr(
        cql_filter.length,
        this.wmsparams.cql_filter.length
      )
      if (
        this.wfsFeature.feature &&
        this.wmsparams.cql_filter !== this.userWfsOrg
      ) {
        rname =
          (this.wfsFeatures.cql_feature![this.wmsparams.cql_filter] &&
            this.wfsFeatures.cql_feature![
              this.wmsparams.cql_filter
            ]!.getProperties().rname) ||
          null
      } else {
        rname = this.userOrgName
      }
      let features = this.wfsFeatures.features![this.wmsparams.cql_filter]
      // console.log(features)
      features.some((f) => {
        let levelid = f!.getProperties().levelid
        if (levelid > 4) {
          return true
        }
        featuresExtent.push({
          org: f!.getProperties().rno,
          levelid,
          coordinate: ol.extent.getCenter(f!.getGeometry().getExtent()),
        })
      })

      this.wfsFeature.cql = this.wmsparams.cql_filter
      this.tool_bar_org = org
      this.wfsFeatures.zooms.forEach((z) => {
        if (z.cql === this.wfsFeature.cql) {
          this.wfsFeature.zoom = z.zoom
        }
      })
      console.log('this.wfsFeature.zoom',this.wfsFeature.zoom)
      if (featuresExtent.length) {
        this.onOrganChanged(org, featuresExtent, rname)
      } else {
        this.onOrganChanged(org, null, rname)
      }
    }
  }

  /**
   * 行政区视图变化
   * @param org
   * @param featuresExtent
   */
  onOrganChanged(org, featuresExtent, rname) {
    console.log(this.wfsFeatures)
    this.addMasklist(org)
    this.resourceVisualService.regionChanged({
      org,
      featuresExtent,
      rname,
    })
    this.utils.setSessionStorage('gis_monitor_org', {
      org,
      featuresExtent,
      rname,
    })
    this.menuService.nextCity(org)
  }

  // 地图拖拽监听函数
  mapPointerDrag = (e) => {
    this.hideListBtnStatus = true
    if (this.operation === 'SearchList') {
      this.resourceVisualService.changeRegionBtnShowStatus(true)
      this.resourceVisualService.changeSearchVisibility(true)
    } else {
      this.resourceVisualService.changeRegionBtnShowStatus(false)
    }
  }

  // 创建编辑标签DOM
  createLabelELe(config: any, mapdata: any) {
    this.kspMap.removeOverlayById(this.labelEditOverlayId)

    const mapLabelEditor = new MapLabelEditor()
    let labelDiv = document.createElement('div')
    mapLabelEditor.addToDom(labelDiv)
    const infoConfig = {
      data: {
        id: this.labelEditOverlayId,
        geometry: config['data']['geometry'],
      },
    }
    this.kspMap.createInfoWindow(infoConfig, labelDiv, [-60, -30])
    mapLabelEditor.initLabelStatus(null, labelDiv)

    // 编辑标签关闭
    mapLabelEditor.onClickClose(() => {
      console.log('关闭', this.labelEditOverlayId)
      if (this.currentLabelFeature) {
        this.kspMap.deleteDrawFeature(this.currentLabelFeature)
        this.currentLabelFeature = null
      }
      this.kspMap.removeOverlayById(this.labelEditOverlayId)
    })

    // 编辑标签图标选择
    mapLabelEditor.onClickIcon((e) => {
      console.log('选择的图标类型', e)
      let type = e
      this.kspMap.updateMarkerFeature(this.currentLabelFeature, {
        img: {
          url: SearchTypeSetting[this.labelType]['mapIcon'][type],
          size: this.labelIconSize,
        },
      })
    })

    // 编辑标签点击取消
    mapLabelEditor.onClickCancel(() => {
      this.kspMap.deleteDrawFeature(this.currentLabelFeature)
      this.currentLabelFeature = null
      this.kspMap.removeOverlayById(this.labelEditOverlayId)
    })

    // 编辑标签点击保存
    mapLabelEditor.onClickSave((data) => {
      if (!data['name']) {
        this.message.create('warning', '请输入标签名称!')
        return
      }
      let tag = {
        tag: {
          name: data['name'],
          remark: data['description'],
          type: Number(data['type']),
          isAllVisible: Number(data['visibility']),
          geom: mapdata['wkt'],
          createUser: this.utils.getSessionStorage(AuthService.keyAI)
            .employeeId,
        },
      }
      this.https
        .postTap(this.https.addTag, tag, '添加标签成功!')
        .subscribe((data) => {
          this.kspMap.removeOverlayById(this.labelEditOverlayId)
          this.resourceVisualService.mapInsectLabel(data)
        })
      // this.resourceVisualService.mapInsectLabel(data)
    })
  }

  // 显示编辑标签窗体
  showCreateLabelWindow(data: any) {
    // this.kspMap.deleteDrawFeature(this.currentLabelFeature)
    const iconId = 'new-icon-' + this.labelIconIdCount
    const config = {
      data: {
        id: iconId,
        geometry: {
          type: 'point',
          points: [{ x: data['position'][0], y: data['position'][1] }],
        },
      },
      styles: {
        bgimg: SearchTypeSetting[this.labelType]['mapIcon'][this.labelIconType],
        width: 32,
        height: 32,
      },
    }
    this.createLabelELe(config, data)
    this.labelIconIdCount += 1
  }

  ngOnDestroy() {
    this.menuService.nextCity(this.authService.getorgano().organNo)
    this.resolutiontSubscription.unsubscribe()
    this.homeInitSubjectSubscription.unsubscribe()
    this.orgTreefarmSubscription.unsubscribe()
    this.spotSubscription.unsubscribe()
    this.organnoSpotSubscription.unsubscribe()
    this.rooterChange.unsubscribe()
    console.log('根组件销毁')
    this.rvService.removeAllModal()
    this.IncidentService.nextPanelCLick('all-detail')
    this.mapUtils.removeMapLayers('panel')
    this.mapUtils.removeVectorLayer('search-primary-class-layer')
    // this.mapUtils.removeMapLayers('panel_searchlabel_point_list')
    this.kspMapService.getKspmap().clearAllTrackLine()
    this.searchPanelServiceSubscription.unsubscribe()
    // this.subscription.unsubscribe()
    // this.kspMap.removeMapEvent('singleclick', this.mapClick)
    this.kspMap.removeMapEvent('pointerdrag', this.mapPointerDrag)
    // this.kspMap.removeMapEvent('pointermove', this.mapPointermove)
    ol.Observable.unByKey(this.singleclick)
    ol.Observable.unByKey(this.pointermove)
    ol.Observable.unByKey(this.resoluption)
    this.baseMapLayerChangedSubscription &&
      this.baseMapLayerChangedSubscription.unsubscribe()
  }

  searchAvailable = false
  onResolutionChanged(evt) {
    // 关闭层级控制首页的显示隐藏
    // let zoom = this.kspMap.getMapZoom()
    // if (zoom < 10 && this.searchAvailable) {
    //   this.searchAvailable = false
    // } else if (zoom >= 10 && !this.searchAvailable) {
    //   this.searchAvailable = true
    //   this.removeSumLayerAndOverlay()
    // }
  }

  showIndexHome() {
    if (this.searchAvailable) {
      this.searchAvailable = false
      this.map.mainMap.getView().fit(this.userWfsExtent, {
        size: this.map.mainMap.getSize(),
        padding: [0, 0, 0, 0],
        duration: 1000,
      })
      this.router.navigate([GIS_HOME_PATH])
    } else {
      if (
        this.userWfszoom === this.kspMap.mainMap.getView().getZoom() &&
        this.wmsparams.cql_filter !== this.userWfsOrg
      ) {
        this.wmsparams.cql_filter = this.userWfsOrg
        // this.wfsFeature.cql = this.userWfsOrg
        this.wfsFeature.rpno = this.wfsFeature.cql
        this.selectcache()
        this.setAdministrative()
        // this.moveed(null)
      }
      this.map.mainMap.getView().fit(this.userWfsExtent, {
        size: this.map.mainMap.getSize(),
        padding: [0, 0, 0, 0],
        duration: 1000,
      })
      // this.mapUtils.setMapCenterAndZoom([12618191.188117, 2648719.790709], 7)
    }
  }

  /**
   * 首页wms-tile
   */
  addGdTile() {
    this.GdTile = new ol.layer.Tile({
      // extent: [-400.0, -28.835980314756398, 223.76142591237294, 400.0],
      minResolution: 565.9956300601204,
      source: new ol.source.TileWMS({
        url: GIS_OVERVIEW_WMS_URL,
        params: {
          LAYERS: 'guangdong',
          TILED: true,
          // SRS: 'EPSG:4326',
          VERSION: '1.1.1',
        },
        tileGrid: new ol.tilegrid.TileGrid({
          tileSize: [256, 256],
          origin: [-400.0, 400.0],
          resolutions: [
            0.00951784402332112, 0.007138383017490841, 0.00475892201166056,
            0.00237946100583028, 0.00118973050291514, 5.9486525145757e-4,

            // 0.15228550437313793,
            // 0.07614275218656896,
            // 0.03807137609328448,
            // 0.01903568804664224,
            // 0.00951784402332112,
            // 0.00475892201166056,
          ],
        }),
        hidpi: false,
        projection: 'EPSG:4326',
        serverType: 'geoserver',
        transition: 0,
      }),
      zIndex: 11,
      // maxResolution: 9.51784402332112e-6,
      // minResolution: 0.01903568804664224,
    })
    this.kspMap.mainMap.addLayer(this.GdTile)
  }

  addAdministrativeLayer() {
    if (this.wmsLayer) {
      this.wmsLayer.getSource().clear()
    }
    if (this.geojsonLayer) {
      this.geojsonLayer.getSource().clear()
    }
    // and isdel=0
    
    let cql_filter = this.wmsparams.cql_filter;
    this.wmsparams.cql_filter = `${cql_filter} and maphide=0`
    let url = '/geoserver/wfs' + '?'
    for (let param in this.wmsparams) {
      url = url + param + '=' + this.wmsparams[param] + '&'
    }
    url = url.slice(0, -1)
    this.wmsparams.cql_filter = cql_filter;
    // 过滤广东省的  林场
    // if (this.wmsparams.cql_filter === 'rpno=44') {
    //   url += ` and rname not like '%25林场%25'`
    // }
    // extent区域参数
    console.log('wmsExtentParams', this.wmsExtentParams)
    let extentUrl = '/geoserver/wfs' + '?'
    for (let param in this.wmsExtentParams) {
      extentUrl = extentUrl + param + '=' + this.wmsExtentParams[param] + '&'
    }
    extentUrl = extentUrl.slice(0, -1)
    console.log('extentUrl',extentUrl)
    this.getCurrentExtent(extentUrl)
    let vectorSource = new ol.source.Vector({
      format: new ol.format.GeoJSON(),
      strategy: ol.loadingstrategy.all,
    })
    $.ajax({
      type: 'GET',
      url: url,
      // '/geoserver/wfs?service=wfs&version=1.1.0&request=GetFeature&typeNames=ksp:t_region&outputFormat=application/json&srsname=EPSG:4326&cql_filter=rpno=4401',
      success: (result) => {
        console.log('成功', result)
        this.wfsFeatures.features[this.wmsparams.cql_filter] = []

        for (let f of result['features']) {
          // let newfeature = new ol.format.GeoJSON().readFeatures(f)
          let feature = new ol.format.GeoJSON().readFeatures(f)
          let geom = feature[0]
            .getGeometry()
            .transform('EPSG:4326', 'EPSG:3857')
          feature[0].setGeometry(geom)
          vectorSource.addFeatures(feature)
          this.wfsFeatures.features[this.wmsparams.cql_filter].push(feature[0])
        }
        // if (result.bbox) {
        //   this.map.mainMap.getView().fit(vectorSource.getExtent(), {
        //     size: this.map.mainMap.getSize(),
        //     padding: [0, 0, 0, 0],
        //     duration: 1000,
        //   }) //居中到geometry视野中
        // }
        this.setAdministrative()
        //   this.viewExtentCount = 1
        // if (this.viewExtentCount === 0) {
        //   this.userWfsExtent = vectorSource.getExtent()
        //   let extent = vectorSource.getExtent()
        //   let center = ol.extent.getCenter(extent)
        //   var r = this.map.mainMap
        //     .getView()
        //     .getResolutionForExtent(extent, this.map.mainMap.getSize())
        //   var minzoom = this.map.mainMap.getView().getZoomForResolution(r)
        //   // this.map.mainMap.getView().setResolution(r)
        //   console.warn('分辨率' + r)
        //   this.utils.setSessionStorage('map-resolution', r)
        //   // this.map.mainMap.getView().setCenter(ol.extent.getCenter(extent))
        //   // this.map.mainMap.getView().setExtent(extent)
        //   // this.map.mainMap.getView().setResolution(r)
        //   // let zoom = this.kspMap.mainMap.getView().getZoom()
        //   // this.map.mainMap.getView().setZoom(zoom)

        //   this.utils.setSessionStorage('map-extent', extent)

        //   let view = new ol.View({
        //     extent: extent,
        //     center: center,
        //     zoom: Math.floor(minzoom),
        //     projection: 'EPSG:3857',
        //     maxZoom: 18,
        //     minZoom: Math.floor(minzoom),
        //     // minZoom: Math.floor(minzoom),
        //     // resolution: r,
        //     // maxResolution: r,
        //     // minResolution: r,
        //   })

        //   this.setMapView(view)
        //   this.toolAfter = true
        // }

        // setTimeout(() => {
        //   this.wfsFeatures.zooms.push({
        //     cql: this.wmsparams.cql_filter,
        //     zoom: Math.floor(this.map.mainMap.getView().getZoom()),
        //   })
        //   this.wfsFeature.zoom = this.map.mainMap.getView().getZoom()
        //   if (this.wmsparams.cql_filter === this.userWfsOrg) {
        //     this.userWfszoom = this.map.mainMap.getView().getZoom()
        //   }
        // }, 1000)
      },
      error: function (jq) {
        console.log('失败', jq)
      },
    })
    this.wmsLayer.getSource().clear()
    this.wmsLayer.setSource(vectorSource)
    this.pointTitleLayer.getSource().clear()
    this.pointTitleLayer.setSource(vectorSource)
    // this.map.mainMap.addLayer(this.wmsLayer)
    // return
  }
  /**
   * @description 重载view
   */
  setMapView(view) {
    this.map.mainMap.setView(view)
    this.resoluption = this.kspMap.mainMap
      .getView()
      .on('change:resolution', (e) => {
        this.resolutionSubject.next(e)
        this.regionLineOnChange()
      })
  }
  /**
   * @description 图层hover Layer
   */
  wmsHoverLayer() {
    this.pointTitleLayer = new ol.layer.Vector({
      // map: this.map.mainMap,
      source: new ol.source.Vector(),
      zIndex: 11,
      style: (feature) => {
        let extent = feature.getGeometry().getExtent()
        let pos = ol.extent.getCenter(extent)
        if (
          this.wmsparams.cql_filter === 'rpno=44' &&
          this.isorgTreefarm &&
          feature.getProperties().rname.indexOf('林场') !== -1
        ) {
          return null
        }
        return new ol.style.Style({
          geometry: new ol.geom.Point(pos),
          text: new ol.style.Text({
            font: '12px Calibri,sans-serif',
            text: feature!.getProperties().rname || '暂无名称',
            padding: [1, 4, 0, 4],

            textAlign: 'center',
            textBaseline: 'bottom',
            //标签的背景填充
            backgroundFill: new ol.style.Fill({
              color: '#014C77',
            }),
            fill: new ol.style.Fill({
              color: '#fff',
            }),
          }),
        })
      },
    })

    this.wmsLayer = new ol.layer.Vector({
      // map: this.map.mainMap,
      source: new ol.source.Vector(),
      zIndex: 11,
      style: (feature: ol.Feature) => {
        if (
          this.wmsparams.cql_filter === 'rpno=44' &&
          this.isorgTreefarm &&
          feature.getProperties().rname.indexOf('林场') !== -1
        ) {
          return null
        }
        let colors = this.kspMap.mainMap.getView().getZoom() >= 9 ? '#FAFB00' : '#5EFFFF';
        return new ol.style.Style({
          geometry: null,
          stroke: new ol.style.Stroke({
            color: colors,
            width: 2,
          }),
        })
      },
    })
    this.map.mainMap.addLayer(this.wmsLayer)
    this.map.mainMap.addLayer(this.pointTitleLayer)
    this.geojsonLayer = new ol.layer.Vector({
      // map: this.map.mainMap,
      source: new ol.source.Vector(),
      zIndex: 11,
      style: new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: '#00F4FF',
          // lineDash: [4],
          width: 1,
        }),
        fill: new ol.style.Fill({
          color: 'rgba(0,244,255, 0.5)',
        }),
      }),
    })
    this.map.mainMap.addLayer(this.geojsonLayer)
    this.masklayer = new ol.layer.Vector({
      source: new ol.source.Vector(),
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(0,0,0, 0.7)',
        }),
        stroke: new ol.style.Stroke({
          color: 'transparent',
        }),
      }),
      zIndex: 999,
    })
    this.kspMap.mainMap.addLayer(this.masklayer)

    this.innerLayer= new ol.layer.Vector({
      source: new ol.source.Vector({}),
      style: new ol.style.Style({ 
        stroke:new ol.style.Stroke({
           width:5,
           color:'rgba(249,250,0,0.4)'
      }),
        fill:new ol.style.Fill({
           color:'rgba(255,0,0,0)'
        })
      }),
        zIndex:2
      });
      this.kspMap.mainMap.addLayer(this.innerLayer);

      //outer
     this.outerLayer = new ol.layer.Vector({
      source: new ol.source.Vector({}),
      style: new ol.style.Style({ 
        stroke:new ol.style.Stroke({
          width:15,
          color:'rgba(249,250,0,0.4)'
      }),
      fill:new ol.style.Fill({
          color:'rgba(255,0,0,0)'
        })
      }),
        zIndex:2
      });
      this.kspMap.mainMap.addLayer(this.outerLayer);



    if(this.userworkinfo=='44'){
      this.masklayer.setVisible(false)
      this.innerLayer.setVisible(false)
      this.outerLayer.setVisible(false)
    }
    // 
  }
  initparams() {
    this.wmsparams = {
      service: 'wfs',
      version: '2.0.0',
      request: 'GetFeature',
      typeNames: 'ksp:t_region',
      srsname: 'EPSG:4326',
      outputFormat: 'application/json',
      cql_filter: 'rpno=44'
    }
  }

  /**
   * 初始化获取当前行政区的wfs服务的参数
   */
  initExtentparams() {
    this.wmsExtentParams = {
      service: 'wfs',
      version: '2.0.0',
      request: 'GetFeature',
      typeNames: 'ksp:t_region',
      srsname: 'EPSG:4326',
      outputFormat: 'application/json',
      cql_filter: 'rno=44'
    }
  }

  /**
   * 获取当前区域的extent
   * @param url geoserver url
   */
  getCurrentExtent(url) {
    let org=this.wmsExtentParams.cql_filter.split('=')[1]
    $.ajax({
      type: 'GET',
      url: url,
      success: (result) => {
        let features = result['features']
        if (Array.isArray(features) && features.length) {
          let featureGeometry = <ol.geom.MultiPolygon>(
            new ol.format.GeoJSON()
              .readFeatures(features[0])[0]
              .getGeometry()
              .transform('EPSG:4326', 'EPSG:3857')
          )
          const extent = featureGeometry.getExtent()
          console.log('this.map.mainMap.getSize()',this.map.mainMap.getSize())
          if(org==this.userworkinfo){
            this.initfeatureGeometry=featureGeometry
            // this.addMask(this.initfeatureGeometry)
          }
          // this.addMask(featureGeometry)
          this.map.mainMap.getView().fit(extent, {
            size: this.map.mainMap.getSize(),
            padding: [0, 0, 0, 0],
            duration: 1000,
          }) //居中到geometry视野中
          if (this.viewExtentCount === 0) {
            this.viewExtentCount = 1
            this.setMapViewByExtent(extent)
          }

          setTimeout(() => {
            this.wfsFeatures.zooms.push({
              cql: this.wmsparams.cql_filter,
              zoom: this.map.mainMap.getView().getZoom(),
              extent,
            })
            this.wfsFeature.zoom = this.map.mainMap.getView().getZoom()
            if (this.wmsparams.cql_filter === this.userWfsOrg) {
              this.userWfszoom = this.map.mainMap.getView().getZoom()
            }
            this.wfsFeature.zoom = this.map.mainMap.getView().getZoom()
          }, 1000)
        }
      },
      error: function (jq) {
        console.log('失败', jq)
      },
    })
  }

  /**
   * 根据给定的extent重新设置map->view
   * @param regionExtent ol.extent
   */
  setMapViewByExtent(regionExtent) {
    this.userWfsExtent = regionExtent
    let extent = regionExtent
    let center = ol.extent.getCenter(extent)
    this.setViewInterval = setInterval(() => {
      if (this.map.mainMap.getSize()[0]) {
        var r = this.map.mainMap
          .getView()
          .getResolutionForExtent(extent, this.map.mainMap.getSize())
        var minzoom = this.map.mainMap.getView().getZoomForResolution(r)
        console.log('地图大小', this.map.mainMap.getSize())
        // if (document.documentElement.clientWidth > 1280) {
        //   clearInterval(this.timers)
        //   this.mapUtils.removeVectorLayer('Personal_point')
        // }
        console.warn('分辨率' + r)
        this.utils.setSessionStorage('map-resolution', r)
        this.utils.setSessionStorage('map-extent', extent)

        let view = new ol.View({
          extent: extent,
          center: center,
          zoom: Math.floor(minzoom),
          projection: 'EPSG:3857',
          maxZoom: 18,
          minZoom: Math.floor(minzoom),
        })
        this.setMapView(view)
        clearInterval(this.setViewInterval)
      }
    }, 50)
    this.toolAfter = true
  }
  addMasklist(org){
    
    if(org&&org!=this.userworkinfo){
      let featureGeometry=null
      for(let key in this.wfsFeatures.cql_feature){
        let par=key.split('=')
        if(org==par[1]){
          featureGeometry=this.wfsFeatures.cql_feature[key].getGeometry()
        }
      }
      this.addMask(featureGeometry)
    }else{
      this.addMask(this.initfeatureGeometry)
    }
  }
  addMask(featureGeometry) {

    this.masklayer.getSource().clear()
    this.innerLayer.getSource().clear()
    this.outerLayer.getSource().clear()
    let vectorSource = new ol.source.Vector({
      features: [
        new ol.Feature({
          geometry: this.erase(featureGeometry),
        }),
      ],
    })
    this.masklayer.setSource(vectorSource)
    let vectorSources=new ol.source.Vector({
      features: [
        new ol.Feature({
          geometry: featureGeometry,
        }),
      ],
    })

   this.innerLayer.setSource(vectorSources)
    this.outerLayer.setSource(vectorSources)
    // $.get(extentUrl, (data) => {
    // })
  }


  erase(geom) {
    var extent = ol.proj.transformExtent(
      [-180, -90, 180, 90],
      'EPSG:4326',
      'EPSG:3857'
    )
    // let extent = this.olMap.getView().calculateExtent()
    console.log(extent)
    for (let i = 0; i < extent.length; i++) {
      extent[0] = extent[0] - 0.04 //左
      extent[1] = extent[1] - 0.04 //下
      extent[2] = extent[2] + 0.04 //右
      extent[3] = extent[3] + 0.04 //上
    }
    var polygonRing = ol.geom.Polygon.fromExtent(<ol.Extent>extent)
    var coords = geom && geom.getCoordinates()
    coords && coords.length &&coords.forEach((coord) => {
      var linearRing = new ol.geom.LinearRing(coord[0])
      polygonRing.appendLinearRing(linearRing)
    })
    return polygonRing
  }
  /**
   * 显隐gdtile
   */
  setLayerConfigVisiblity() {
    let zoom = this.kspMap.mainMap.getView().getZoom() //获取当前地图的缩放级别
    if (this.GdTile) {
      if (zoom <= 8) {
        this.GdTile.setVisible(true && this.isShowGdTile)
        this.masklayer.setVisible(false)
        this.innerLayer.setVisible(false)
        this.outerLayer.setVisible(false)
        
        setTimeout(() => {
          this.map.mainMap.render()
        }, 500)
      } else {
        this.GdTile.setVisible(false)
        this.masklayer.setVisible(true)
        this.innerLayer.setVisible(true)
        this.outerLayer.setVisible(true)
        
        setTimeout(() => {
          this.map.mainMap.render()
        }, 500)
      }
    }
  }
  queryPropagate(id) {
    this.https
      .post(this.https.queryPropagate, {
        messageName: 'queryPropagate',
        equipid: id,
      })
      .subscribe((data) => {
        if (data['code'] === '0000') {
          this.dataList = []
          if (data['propagate'] && data['propagate']['ledword']) {
            JSON.parse(data['propagate']['ledword']).map((l) => {
              if (l.isuse) {
                data['propagate']['ledtext'] = l.text
                return
              }
            })
          }
          this.dataList = data['propagate']
          this.isVisible = true
        }
      })
  }

  addRegionLineLayer(): any {
    this.addRegionLineWmsTileLayer()
  }

  regionLayerMap = {
    '2': null,
    '3': null,
    '4': null,
  }
  getRegionLayerByLevelId(levelId, visible) {
    return new ol.layer.Tile({
      visible,
      source: new ol.source.TileWMS({
        crossOrigin: 'anonymous',
        params: {
          LAYERS: 'ksp:t_region',
          TILED: false,
          SRS: 'EPSG:4326',
          WIDTH: '768',
          HEIGHT: '523',
          REQUEST: 'GetMap',
          format: 'image/png',
          cql_filter: `levelid=${levelId} and rname not like '%林场%'`,
        },
        url: '/geoserver/ksp/wms',
      }),
    })
  }
  addRegionLineWmsTileLayer() {
    // for (const key in this.regionLayerMap) {
    //   this.regionLayerMap[key] = this.getRegionLayerByLevelId(key, key === '2')
    //   this.olMap.addLayer(this.regionLayerMap[key])
    // }
  }

  levelid = 2
  setRegionLayerMapVisible(levelId) {
    this.levelid = levelId
    for (const key in this.regionLayerMap) {
      if (this.regionLayerMap[key]) {
        this.regionLayerMap[key].setVisible(+key === levelId)
      }
    }
  }

  regionLineOnChange = () => {
    console.log('????')
    const zoom = this.olMap.getView().getZoom()
    if (zoom <= 8 && this.levelid !== 2) {
      // 9
      this.setRegionLayerMapVisible(2)
    } else if (zoom > 8 && zoom <= 10 && this.levelid !== 3) {
      //10
      this.setRegionLayerMapVisible(3)
    } else if (zoom > 10 && this.levelid !== 4) {
      // 14
      this.setRegionLayerMapVisible(4)
    } else {
    }
  }


}




<template>
  <div id="olMap"></div>
</template>
 
<script>
import 'ol-ext/dist/ol-ext.min.css';
import { Map, View } from "ol";
import OSM from "ol/source/OSM"
import Stamen from 'ol/source/Stamen'
import TileLayer from "ol/layer/Tile"
import GeoJSON from "ol/format/GeoJSON";
import Fill from "ol/style/Fill";
import Mask from 'ol-ext/filter/Mask'
import Crop from 'ol-ext/filter/Crop'
import {createTDTImg} from '@/components/map/olMap/modules/basemap'
export default {
  name: "ol-蒙版图层",
  data() {
    return {
      mapObj:{
        map:null,
        view:null,
      },
      namespace:'testKH',
      layername:'shushan',
      baseUrl:'http://localhost:7777/geoserver/testKH/'
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap(){
      const osmBaseLayer = new TileLayer({
        source:new OSM()
      })
      this.mapObj.view = new View({
        center: [117.28, 31.86],
        zoom: 8,
        projection: 'EPSG:4326',
      })
      this.mapObj.map = new Map({
        layers :[osmBaseLayer],
        view:this.mapObj.view,
        target:'olMap'
      })
      //添加蒙版图层
      let f = new GeoJSON().readFeature(require('@/assets/indexMap.json').features[0])
      var mask = new Mask({
        feature: f,
        wrapX: true,
        inner: false,
        fill: new Fill({ color:[255,255,255,0.6] })
      });
      var crop = new Crop({
        feature: f,
        wrapX: true,
        inner: false
      });
      // 若不加天地图就直接将osmlayer 使用addFilter 就行
      // osmBaseLayer.addFilter(crop);
      // osmBaseLayer.addFilter(mask);
 
      let tdtImgLayer = createTDTImg();
      tdtImgLayer.addFilter(crop);
      tdtImgLayer.addFilter(mask);
      this.mapObj.map.addLayer(tdtImgLayer)
    }
  },
  components: {}
}
</script>
 
<style scoped>
#olMap{
  height:100%;
  width: 100%;
}
</style>